/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.model;

import offset.nodes.client.model.DummyContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

/**
 *
 * @author Walter Ltgenau
 */
public class XmlCharacterFilter extends DummyContentHandler {
    ContentHandler handler;
    
    public XmlCharacterFilter( ContentHandler handler ) {
        this.handler = handler;
    }
    
    public static String filterAttributeValue(String value) throws SAXException {
        return filterCharacters(value.toCharArray(), 0, value.length());
    }
    
    public static String filterCharacters(char[] chars, int start, int length) throws SAXException {
        StringBuffer buf = new StringBuffer();
        for (int counter = start; counter < length; counter++) {
            switch (chars[counter]) {
            // Character level entities.
                case '<':
                    buf.append("&lt;");
                    break;

                case '>':
                    buf.append("&gt;");
                    break;

                case '&':
                    buf.append("&amp;");
                    break;

                case '\"':
                    buf.append("&quot;");
                    break;

            // Special characters
                case '\n':
                case '\t':
                case '\r':
                    buf.append(chars[counter]);
                    break;

                default:
                    if (chars[counter] < ' ' || chars[counter] > 127) {
                        buf.append("&#");
                        buf.append(String.valueOf((int) chars[counter]));
                        buf.append(";");
                    } else {
                        buf.append(chars[counter]);
                    }
                    break;
            }
        }
        
        return buf.toString();
    }
    

    @Override
    public void characters(char[] chars, int start, int length) throws SAXException {
        String result = filterCharacters(chars, start, length);
        handler.characters(result.toCharArray(), 0, result.length());
    }
    
}
